/**
 * FileName: BeanCopierUtils
 * Author:   miao_jin
 * Date:     2020/5/27 9:23
 * Description: //模块目的、功能描述
 */
package com.wangc.commons.utils;

import com.google.common.collect.Maps;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.beans.BeanMap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * cglib对象拷贝工具类
 *
 * @author miao_jin
 */
public class BeanUtils {

    // 使用多线程安全的Map来缓存BeanCopier，由于读操作远大于写，所以性能影响可以忽略
    private static final Map<String, BeanCopier> BEAN_COPIER_CACHE = new ConcurrentHashMap<>();

    /**
     * 通过cglib BeanCopier形式,使用cglib拷贝，同属性同类型拷贝(不使用自定义Converter)
     *
     * @param source 源转换的对象
     * @param target 目标转换的对象
     */
    public static <O, T> T copyProperties(O source, Class<T> target) {
        T instance;
        try {
            BeanCopier copier = getBeanCopier(source.getClass(), target);
            instance = target.getDeclaredConstructor().newInstance();
            copier.copy(source, instance, null);
        } catch (Exception e) {
            throw new RuntimeException("bean copy failed：" + e.getMessage());
        }
        return instance;
    }

    /**
     * @param source    原数据，list集合
     * @param target    接收复制的数据实体类属性，会自动转换成list集合
     * @param sourceKey 原数据的实体类属性，为了防止空数据获取该属性报错
     * @return
     */
    public static <O, T> List<T> copyPropertiesOfList(List<O> source, Class<T> target, Class<O> sourceKey) {
        List<T> targets = new ArrayList<>();
        try {
            BeanCopier copier = getBeanCopier(sourceKey, target);
            for (O bean : source) {
                T instance = target.getDeclaredConstructor().newInstance();
                copier.copy(bean, instance, null);
                targets.add(instance);
            }
        } catch (Exception e) {
            throw new RuntimeException("list copy failed：" + e.getMessage());
        }
        return targets;
    }


    /**
     * 通过cglib BeanMap形式将javabean对象装换为map
     *
     * @param bean 源转换的对象
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = Maps.newHashMap();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }

    /**
     * 将map装换为javabean对象
     *
     * @param map 源数据map
     * @param bean 需转换的对象
     */
    public static <T> T mapToBean(Map<String, Object> map, T bean) {
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;
    }

    private static BeanCopier getBeanCopier(Class<?> sourceClass, Class<?> targetClass) {
        String beanKey = generateKey(sourceClass, targetClass);
        BeanCopier copier;
        if (!BEAN_COPIER_CACHE.containsKey(beanKey)) {
            copier = BeanCopier.create(sourceClass, targetClass, false);
            BEAN_COPIER_CACHE.putIfAbsent(beanKey, copier);
        } else {
            copier = BEAN_COPIER_CACHE.get(beanKey);
        }
        return copier;
    }

    /**
     * 两个类的全限定名拼接起来构成Key
     *
     * @param sourceClass
     * @param targetClass
     */
    private static String generateKey(Class<?> sourceClass, Class<?> targetClass) {
        return sourceClass.getName() + targetClass.getName();
    }

}
